package com.example.light.system.service;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.light.system.common.Result;
import com.example.light.system.dto.permissionTree;
import com.example.light.system.entity.permission;
import com.example.light.system.mapper.PermissionMapper;
import com.example.light.system.service.impl.IPermissionService;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

@Service
public class permissionService extends ServiceImpl<PermissionMapper, permission> implements IPermissionService {
    @Resource
    PermissionMapper permissionMapper;

    /**
     * 所有页面权限列表
     * @return
     */
    public Result<ArrayList<permissionTree>> searchAllPermission(){
        List<permission> permissionList = permissionMapper.selectList(null);
        // 创建存放父路由和子路由的数组链表
        ArrayList<permissionTree> parentRouterList = new ArrayList<>();
        ArrayList<permissionTree> childRouterList = new ArrayList<>();
        // 遍历权限列表中的parentId字段是否存在来判断该页面是否属于二级路由
        Iterator<permission> iterator = permissionList.iterator();
        while (iterator.hasNext()){
            permission next = iterator.next();
            if (next.getParentId() == null){
                permissionTree permissionTree = new permissionTree();
                permissionTree.setPermissionId(next.getPermissionId());
                permissionTree.setPermissionName(next.getPermissionName());
                parentRouterList.add(permissionTree);
            }else {
                permissionTree permissionTree = new permissionTree();
                permissionTree.setPermissionId(next.getPermissionId());
                permissionTree.setPermissionName(next.getPermissionName());
                permissionTree.setParentId(next.getParentId());
                childRouterList.add(permissionTree);
            }
        }
        // 匹配一级路由以及二级路由
        Iterator<permissionTree> parentIterator = parentRouterList.iterator();
        while (parentIterator.hasNext()){
            ArrayList<permissionTree> childRouterSet = new ArrayList<>();
            permissionTree parentRouter = parentIterator.next();
            Iterator<permissionTree> childIterator = childRouterList.iterator();
            while (childIterator.hasNext()){
                permissionTree childRouter = childIterator.next();
                if (childRouter.getParentId() == parentRouter.getPermissionId()){
                    childRouterSet.add(childRouter);
                }
            }
            parentRouter.setChildRouter(childRouterSet);
        }
        return Result.success(parentRouterList);
    }

    // 通过角色id查询权限id
    public Result<ArrayList<Integer>> searchRolePermission(Integer roleId){
        ArrayList<Integer> arrayList = permissionMapper.selectByRoleId(roleId);
        return Result.success(arrayList);
    }
}
